package com.wzy.netty.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.stream.Stream;

/**
 * 描述  : Scattering:  将数据写入到buffer时,可以采用buffer数组,依次写入[分散]
 * gathering: 从buffer读取数据时,可以采用buffer数组,依次读
 * 创建人:    Wzy
 * 创建时间: 2020-06-10  15:42
 */
@Slf4j
public class ScatteringAndGatheringTest {
    public static void main(String[] args) throws IOException {
        //使用server
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);

        serverSocketChannel.socket().bind(inetSocketAddress);
        //创建buffer 数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);
        //等待客户端连接
        SocketChannel socketChannel = serverSocketChannel.accept();

        // 假定从客户端接收8个字节
        int msgLen = 8;

        while (true) {
            int byteRead = 0;
            if (byteRead < msgLen) {
                long l = socketChannel.read(byteBuffers);
                byteRead += l;
                System.out.println("byteRead 读取数量 = " + byteRead);
                Stream.of(byteBuffers).map(buffer -> "position=" + buffer.position() + ",limit=" + buffer.limit()).forEach(System.out::println);
            }
            //将所有的buffer反转
            for (ByteBuffer byteBuffer : byteBuffers) {
                byteBuffer.flip();
            }
            //将数据读出显示到客户端
            long byteWrite = 0;
            while (byteWrite < msgLen) {
                long l = socketChannel.write(byteBuffers);
                byteWrite += l;
            }
            //将所有的buffer复位
            Stream.of(byteBuffers).forEach(Buffer::clear);
            System.out.println("byteRead=" + byteRead + "byteWrite=" + byteWrite + "mesLen=" + msgLen);
        }


    }
}
